import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, ValidationErrors, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd';
import { Observable, Observer } from 'rxjs';
import { CustomService } from '../service/custom.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit {

  loginValidateForm!: FormGroup;
  registerValidateForm!: FormGroup;
  passwordValidateForm!: FormGroup;
  formType: number = 1;
  code: string | null = null;
  codePhone: string | null = null;
  codeButtonText: string = '点击获取验证码';
  codeButtonDisabled: boolean = false;
  codeIntervalSecond: number = 120;
  remember: boolean = false;
  agreement: boolean = false;
  isShowAgreement: boolean = false;
  maxHeight = (window.innerHeight - 200) + 'px';

  loginForm(): void {
    for (const i in this.loginValidateForm.controls) {
      this.loginValidateForm.controls[i].markAsDirty();
      this.loginValidateForm.controls[i].updateValueAndValidity();
    }
    if (this.loginValidateForm.status == "VALID") {
      var data = this.loginValidateForm.value;
      this.customService.login(data).subscribe(result => {
        window.sessionStorage['ticket'] = result['data']['access_token'];
        window.sessionStorage['userid'] = result['data']['userId'];
        window.sessionStorage['username'] = result['data']['userName'];
        window.sessionStorage['phone'] = result['data']['phone'];
        if (this.remember) {
          window.localStorage['username'] = data['username'];
          window.localStorage['password'] = data['password'];
          window.localStorage['remember'] = this.remember;
        }
        else {
          if (window.localStorage['username'])
            window.localStorage.removeItem('username')
          if (window.localStorage['password'])
            window.localStorage.removeItem('password')
          if (window.localStorage['remember'])
            window.localStorage.removeItem('remember')
        }
        this.router.navigateByUrl('/main/index')
      });
    }
  }

  registerForm(): void {
    for (const i in this.registerValidateForm.controls) {
      this.registerValidateForm.controls[i].markAsDirty();
      this.registerValidateForm.controls[i].updateValueAndValidity();
    }
    if (this.registerValidateForm.status == "VALID" && this.agreement) {
      var data = this.registerValidateForm.value;
      if (this.code && this.codePhone && this.codePhone === data['phone'] && this.code === data['code']) {
        data['userName'] = data['email'];
        data['isPhoneAuth'] = true;
        this.customService.register(data).subscribe(result => {
          if (result['code'] === 'success') {
            this.modalService.success({
              nzTitle: '注册提示',
              nzContent: '注册成功，请登录。'
            });
            this.formType = 1;
          }
        });
      }
      else if (!this.code) {
        this.modalService.info({
          nzTitle: '注册提示',
          nzContent: '请先获取验证码！'
        });
      } else {
        this.modalService.info({
          nzTitle: '注册提示',
          nzContent: '验证码输入错误！'
        });
      }
    }
    else if (!this.agreement) {
      this.modalService.info({
        nzTitle: '注册提示',
        nzContent: '请先阅读《用户使用协议》和《隐私协议》'
      });
    }
  }

  passwordForm(): void {
    for (const i in this.passwordValidateForm.controls) {
      this.passwordValidateForm.controls[i].markAsDirty();
      this.passwordValidateForm.controls[i].updateValueAndValidity();
    }
    if (this.passwordValidateForm.status == "VALID") {
      var data = this.passwordValidateForm.value;
      if (this.code && this.codePhone && this.codePhone === data['userName']) {
        this.customService.resetPassword(data).subscribe(result => {
          if (result['code'] === 'success') {
            this.modalService.success({
              nzTitle: '找回密码提示',
              nzContent: '密码重设成功'
            });
            this.formType = 1;
          }
          else {
            this.modalService.info({
              nzTitle: '找回密码提示',
              nzContent: result['data']
            });
          }
        });
      }
      else if (!this.code) {
        this.modalService.info({
          nzTitle: '找回密码提示',
          nzContent: '请先获取验证码！'
        });
      }
    }
  }

  changeForm(value: number) {
    this.formType = value;
  }

  sendCode() {
    var that = this;
    this.registerValidateForm.controls['phone'].markAsDirty();
    this.registerValidateForm.controls['phone'].updateValueAndValidity();
    console.log(this.registerValidateForm.controls['phone'].status);
    if (this.registerValidateForm.controls['phone'].status === 'VALID') {
      this.codeIntervalSecond = 120;
      this.codeButtonDisabled = true;
      this.customService.sendPhone(this.registerValidateForm.controls['phone'].value).subscribe(result => {
        if (result['code'] === 'success') {
          this.code = result['data']['code'];
          this.codePhone = this.registerValidateForm.controls['phone'].value;
          var a = setInterval(() => {
            that.codeIntervalSecond = that.codeIntervalSecond - 1;
            that.codeButtonText = `${that.codeIntervalSecond}秒后重发`;
            if (that.codeIntervalSecond <= 0) {
              that.codeButtonText = '点击获取验证码';
              this.codeButtonDisabled = false;
              window.clearInterval(a);
            }
          }, 1000);
        }
        else {
          this.codeButtonDisabled = false;
          this.modalService.error({
            nzTitle: '注册提示',
            nzContent: '发送验证码失败'
          });
        }
      });
    }
  }

  sendCode2() {
    var that = this;
    this.passwordValidateForm.controls['userName'].markAsDirty();
    this.passwordValidateForm.controls['userName'].updateValueAndValidity();
    if (this.passwordValidateForm.controls['userName'].status === 'VALID') {
      this.codeIntervalSecond = 120;
      this.codeButtonDisabled = true;
      this.customService.sendAccount(this.passwordValidateForm.controls['userName'].value).subscribe(result => {
        if (result['code'] === 'success') {
          this.code = '已获取';
          this.codePhone = this.passwordValidateForm.controls['userName'].value;
          var a = setInterval(() => {
            that.codeIntervalSecond = that.codeIntervalSecond - 1;
            that.codeButtonText = `${that.codeIntervalSecond}秒后重发`;
            if (that.codeIntervalSecond <= 0) {
              that.codeButtonText = '点击获取验证码';
              this.codeButtonDisabled = false;
              window.clearInterval(a);
            }
          }, 1000);
        }
        else {
          this.codeButtonDisabled = false;
          this.modalService.error({
            nzTitle: '信息提示',
            nzContent: result['data']
          });
        }
      });
    }
  }

  showAgreement() {
    this.isShowAgreement = true;
  }

  closeAgreement() {
    this.isShowAgreement = false;
  }

  userNameAsyncValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      this.customService.exists(control.value).subscribe(result => {
        if (result['data']) {
          observer.next({ exists: true, duplicated: true });
        }
        else {
          observer.next(null);
        }
        observer.complete();
      });
    });

  constructor(
    private fb: FormBuilder,
    private customService: CustomService,
    private router: Router,
    private modalService: NzModalService
  ) { }

  ngOnInit(): void {
    var username = null;
    var password = null;
    if (window.localStorage['username'])
      username = window.localStorage['username'];
    if (window.localStorage['password'])
      password = window.localStorage['password'];
    if (window.localStorage['remember'])
      this.remember = window.localStorage['remember'];
    this.loginValidateForm = this.fb.group({
      username: [username, [Validators.required]],
      password: [password, [Validators.required, Validators.pattern(/^[0-9a-zA-Z]{4,20}$/)]]
    });
    this.registerValidateForm = this.fb.group({
      email: [null, [Validators.email, Validators.required]],//, [this.userNameAsyncValidator]
      password: [null, [Validators.required, Validators.pattern(/^[0-9a-zA-Z]{4,20}$/)]],
      phone: [null, [Validators.required, Validators.pattern(/^13[0-9]{9}$|14[0-9]{9}$|15[0-9]{9}$|16[0-9]{9}$|17[0-9]{9}$|18[0-9]{9}$|19[0-9]{9}$/)]],
      code: [null, [Validators.required, Validators.pattern(/^[0-9]{6}$/)]]
    });
    this.passwordValidateForm = this.fb.group({
      userName: [null, [Validators.required]],
      password: [null, [Validators.required, Validators.pattern(/^[0-9a-zA-Z]{4,20}$/)]],
      code: [null, [Validators.required, Validators.pattern(/^[0-9]{6}$/)]]
    });
  }

}
